﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data;

namespace RBAC.APP
{
    public class UserDepartment
    {
        #region Fields
        /// <summary>
        /// 用户Id
        /// </summary>
        private string userId;
        /// <summary>
        /// 用户Id
        /// </summary>
        public string UserId
        {
            get { return userId; }
            //set { userId = value; }
        }
        /// <summary>
        /// 当前用户所有栏目array
        /// </summary>
        private ArrayList allDepartmentArray;
        /// <summary>
        /// 当前用户栏目
        /// </summary>
        private string currentRole;
        /// <summary>
        /// 当前用户栏目
        /// </summary>
        public string CurrentRole
        {
            get { return currentRole; }
        }
        #endregion Fields

        #region Constructor
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userId">用户Id</param>
        public UserDepartment(string userId)
        {
            //赋值userId，并获得此userId的所有department.
            this.userId = userId;
            this.allDepartmentArray = new ArrayList();
            this.allDepartmentArray.Clear();
            this.allDepartmentArray = UserDepartment.GetAllDepartmentArrayofUser(userId);
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="currentRole">当前角色</param>
        public UserDepartment(string userId, string currentRole)
        {
            //赋值userId，与当前Role
            this.userId = userId;
            this.currentRole = currentRole;
            this.allDepartmentArray = new ArrayList();
            this.allDepartmentArray.Clear();
            this.allDepartmentArray = UserDepartment.GetAllDepartmentArrayofUserRole(userId, currentRole);
        }

        #endregion Constructor

        #region NonstaticFunctions
        /// <summary>
        /// 当前用户的所有栏目
        /// </summary>
        public List<Department> GetDepartmentofUser
        {
            get
            {
                if (string.IsNullOrEmpty(this.currentRole))
                    return UserDepartment.GetAllDepartmentofUser(this.userId);
                else
                    return UserDepartment.GetAllDepartmentofUserRole(this.userId, this.currentRole);
            }
        }

        /// <summary>
        /// 当前用户的所有栏目列表
        /// </summary>
        public ArrayList GetDepartmentArrayofUser
        {
            get
            {
                if (string.IsNullOrEmpty(this.currentRole))
                    return UserDepartment.GetAllDepartmentArrayofUser(this.userId);
                else
                    return UserDepartment.GetAllDepartmentArrayofUserRole(this.userId, this.currentRole);
            }
        }

        /// <summary>
        /// 当前用户是否包含某个栏目
        /// </summary>
        /// <param name="testDepartment">测试栏目</param>
        public bool HasDepartment(string testDepartment)
        {
            if (string.IsNullOrEmpty(testDepartment))
                return false;
            if (this.allDepartmentArray.Contains(testDepartment.Trim()))
                return true;
            return false;
        }

        /// <summary>
        /// 挑选某个栏目
        /// </summary>
        /// <param name="department">栏目Id</param>
        public UserRole this[string department]
        {
            get
            {
                if (string.IsNullOrEmpty(department)) return null;
                if (!HasDepartment(department)) return null;
                UserRole myUserRole = new UserRole(this.userId, department);
                return myUserRole;
            }
        }

        /// <summary>
        /// 为当前用户当前角色添加栏目
        /// </summary>
        /// <param name="newDepartment">需添加的栏目Id</param>
        public int AddDepartment(string newDepartment)
        {
            //*****10121*****
            //向表SURD添加记录
            //（1）参数：userId：当前userId。
            //（2）参数：roleId：当前currentRole。（非常有可能此项不存在）
            //（3）参数：departId：newDepartment。
            //以上三者必须都存在（存在于相应的数据库中），且不能为空。否则返回101212.
            //（4）检测SURD表中，是否已有此记录。若已有，返回101213.
            //（5）向表：SURD中添加记录，成功返回101211，失败返回101219
            //--------------------------------------------------------
            //需Log的情况：101211，101219
            if (string.IsNullOrEmpty(userId))
                return 101212;
            if (string.IsNullOrEmpty(currentRole))
                return 101212;
            if (string.IsNullOrEmpty(newDepartment))
                return 101212;
            if (User.ReadUser(userId) == null)
                return 101212;
            if (Role.ReadRole(currentRole) == null)
                return 101212;
            if (Department.ReadDepartment(newDepartment) == null)
                return 101212;
            RBAC.ORM.DAL.SURD OptSURD = new ORM.DAL.SURD();
            DataSet ds = OptSURD.GetList("userID='" + userId + "' and roleID='" + currentRole + "' and departID='" + newDepartment+"'");
            if (ds.Tables[0].Rows.Count == 0)
            {
                RBAC.ORM.Model.SURD mySURD = new ORM.Model.SURD();
                mySURD.id = OptSURD.GetMaxId() + 1;
                mySURD.roleID = currentRole;
                mySURD.userID = userId;
                mySURD.departID = newDepartment;
                bool ok = OptSURD.Add(mySURD);
                if (ok)
                {
                    Operator.MakeLog(ObjectType.SURD, "101211" + currentRole);
                    return 101211;
                }
                else
                {
                    Operator.MakeLog(ObjectType.SURD, "101219" + currentRole);
                    return 101219;
                }
            }
            else
                return 101213;
        }
        /// <summary>
        /// 为当前用户当前角色删除栏目
        /// </summary>
        /// <param name="oldDepartment">需删除的栏目Id</param>
        public int DeleteDepartment(string oldDepartment)
        {
            //*****10122*****
            //从表SURD中删除记录
            //（1）参数：userId：当前userId。
            //（2）参数：departId：参数oldDepartment。
            //以上二者必须都存在，且不能为空。否则返回101222.
            //（3）参数：roleId：当前currentRole。（非常有可能此项不存在）
            //          若currentRole不为空且存在，则删除表SURD中相应的一条记录。
            //                                检测SURD表中，是否已有此记录。若没有，返回101223.
            //          若currentRole为空，则删除表：SURD中此用户此栏目的所有记录。
            //                                若在其中发生错误，返回101224
            //（4）从表：SURD中删除记录，成功返回101221，失败返回101229
            //--------------------------------------------------------
            //需Log的情况：101221，101229，101224
            RBAC.ORM.DAL.SURD OptSURD = new ORM.DAL.SURD();
            if (string.IsNullOrEmpty(userId))
                return 101222;
            if (string.IsNullOrEmpty(oldDepartment))
                return 101222;
            if (User.ReadUser(userId) == null)
                return 101222;
            if (Department.ReadDepartment(oldDepartment) == null)
                return 101222;
            if (string.IsNullOrEmpty(currentRole))
            {
                DataSet ds = OptSURD.GetList("userID='" + userId + "' and departID='" + oldDepartment + "'");
                if (ds.Tables[0].Rows.Count == 0)
                {
                    Operator.MakeLog(ObjectType.SURD, "101229" + currentRole);
                    return 101229;
                }
                else
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        bool ok = OptSURD.Delete(decimal.Parse(ds.Tables[0].Rows[i]["id"].ToString()));
                        if (!ok)
                        {
                            Operator.MakeLog(ObjectType.SURD, "101224" + currentRole);
                            return 101224;
                        }
                    }
                    Operator.MakeLog(ObjectType.SURD, "101221" + currentRole);
                    return 101221;
                }
            }
            else
            {
                DataSet ds = OptSURD.GetList("userID='" + userId + "' and departID='" + oldDepartment + "' and roleID='" + currentRole + "'");
                if (ds.Tables[0].Rows.Count == 0)
                    return 101223;
                bool ok = OptSURD.Delete(decimal.Parse(ds.Tables[0].Rows[0]["id"].ToString()));
                if (ok)
                {
                    Operator.MakeLog(ObjectType.SURD, "101221" + currentRole);
                    return 101221;
                }
                else
                {
                    Operator.MakeLog(ObjectType.SURD, "101229" + currentRole);
                    return 101229;
                }
            }
        }
        #endregion NonstaticFunctions

        #region StaticFunctions
        /// <summary>
        /// 获得某个用户的所有栏目列表
        /// </summary>
        /// <param name="userId">用户Id</param>
        public static ArrayList GetAllDepartmentArrayofUser(string userId)
        {
            //根据SURD表，获得某个用户的所有DepartmentId，所得结果放入Arraylist，按照DepartmentId升序排列
            //参数不能为空，判定用户是否存在，用户不存在直接返回null。
            if (string.IsNullOrEmpty(userId))
                return null;
            else
            {
                if (User.ReadUser(userId) == null)
                    return null;
                RBAC.ORM.DAL.SURD OptSURD = new ORM.DAL.SURD();
                ArrayList myArrayList = new ArrayList();
                DataSet ds = OptSURD.GetList("userID='" + userId + "' order by departID asc");
                if (ds.Tables[0].Rows.Count == 0)
                    return null;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (myArrayList.Contains(ds.Tables[0].Rows[i]["departID"].ToString()))
                        continue;
                    myArrayList.Add(ds.Tables[0].Rows[i]["departID"].ToString());
                }
                return myArrayList;
            }
        }
        /// <summary>
        /// 获得某个用户的所有栏目
        /// </summary>
        /// <param name="userId">用户Id</param>
        public static List<Department> GetAllDepartmentofUser(string userId)
        {
            //调用函数GetAllDepartmentArrayofUser，将返回结果制成Department对象泛型返回
            //参数不能为空，判定用户是否存在，用户不存在直接返回null。
            if (string.IsNullOrEmpty(userId))
                return null;
            else
            {
                if (User.ReadUser(userId) == null)
                    return null;
                List<Department> myListDepartment = new List<Department>();
                ArrayList myArrayList = new ArrayList();
                myArrayList = UserDepartment.GetAllDepartmentArrayofUser(userId);
                if (myArrayList == null)
                    return null;
                else
                {
                    for (int i = 0; i < myArrayList.Count; i++)
                    {
                        myListDepartment.Add(Department.ReadDepartment(myArrayList[i].ToString()));
                    }
                    return myListDepartment;
                }

            }
        }
        /// <summary>
        /// 获得某个用户某个角色的所有栏目列表
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="userRole">角色Id</param>
        public static ArrayList GetAllDepartmentArrayofUserRole(string userId, string userRole)
        {
            //根据SURD表，获得某个用户某个角色下的所有DepartmentId，所得结果放入Arraylist，按照DepartmentId升序排列
            //参数不能为空，判定用户和角色是否存在，只要有一个不存在直接返回null。
            if (string.IsNullOrEmpty(userId))
                return null;
            else if (string.IsNullOrEmpty(userRole))
                return null;
            else
            {
                if (User.ReadUser(userId) == null)
                    return null;
                else if (Role.ReadRole(userRole) == null)
                    return null;
                else
                {
                    RBAC.ORM.DAL.SURD OptSURD = new ORM.DAL.SURD();
                    ArrayList myArrayList = new ArrayList();
                    DataSet ds = OptSURD.GetList("userID='" + userId + "' and roleID='" + userRole + "' order by departID asc");
                    if (ds.Tables[0].Rows.Count == 0)
                        return null;
                    else
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (myArrayList.Contains(ds.Tables[0].Rows[i]["departID"].ToString()))
                                continue;
                            myArrayList.Add(ds.Tables[0].Rows[i]["departID"].ToString());
                        }
                        return myArrayList;
                    }
                }
            }
        }
        /// <summary>
        /// 获得某个用户某个角色的所有栏目
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="userRole">角色Id</param>
        public static List<Department> GetAllDepartmentofUserRole(string userId, string userRole)
        {
            //调用函数GetAllDepartmentArrayofUserRole，将返回结果制成Department对象泛型返回
            //参数不能为空，判定用户和角色是否存在，只要有一个不存在直接返回null。
            if (string.IsNullOrEmpty(userId))
                return null;
            else if (string.IsNullOrEmpty(userRole))
                return null;
            else
            {
                if (User.ReadUser(userId) == null)
                    return null;
                else if (Role.ReadRole(userRole) == null)
                    return null;
                else
                {
                    List<Department> myListDepartment = new List<Department>();
                    ArrayList myArrayList = new ArrayList();
                    myArrayList = UserDepartment.GetAllDepartmentArrayofUserRole(userId, userRole);
                    if (myArrayList == null)
                        return null;
                    else
                    {
                        for (int i = 0; i < myArrayList.Count; i++)
                        {
                            myListDepartment.Add(Department.ReadDepartment(myArrayList[i].ToString()));
                        }
                        return myListDepartment;
                    }
                }
            }
        }
        #endregion StaticFunctions
    }
}
